package com.pay.online.online_pay.wxpay

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import com.pay.online.online_pay.OnlinePayPlugin
import com.pay.online.online_pay.onlinepay.OnlinePayResultInfo
import com.pay.online.online_pay.onlinepay.OnlinePayResultType
import com.pay.online.online_pay.onlinepay.OnlinePayType
import com.tencent.mm.opensdk.constants.ConstantsAPI
import com.tencent.mm.opensdk.modelbase.BaseReq
import com.tencent.mm.opensdk.modelbase.BaseResp
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler

open class WechatPayActivity : Activity(), IWXAPIEventHandler {

    private val wxPay by lazy { WechatPay.getInstance() }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        wxPay?.handleIntent(intent, this)
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        wxPay?.handleIntent(intent, this)
    }

    override fun onReq(req: BaseReq?) {}

    override fun onResp(resp: BaseResp?) {
        if (resp?.type == ConstantsAPI.COMMAND_PAY_BY_WX) {
            val payResult = OnlinePayResultInfo().apply {
                onlinePayType = OnlinePayType.WechatPay
                when (resp.errCode) {
                    0 -> {
                        message = "微信支付成功"
                        resultType = OnlinePayResultType.Success
                    }
                    -1 -> {
                        message = "微信支付失败, 错误：" + resp.errStr
                        resultType = OnlinePayResultType.Error
                    }
                    -2 -> {
                        message = "您已取消微信支付"
                        resultType = OnlinePayResultType.Canceled
                    }
                }
            }
            sendBroadcast(
                Intent(OnlinePayPlugin.ACTION_NOTIFY_PAY_RESULT)
                    .putExtra("pay_result", payResult)
            )
        }
        finish()
    }

}